package com.dotstone.chipism.ui.timing;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dotstone.chipism.R;
import com.dotstone.chipism.activity.BaseActivity;
import com.dotstone.chipism.bean.HttpURL;
import com.dotstone.chipism.dialog.SVProgressHUD;
import com.dotstone.chipism.ui.timing.bean.AddTimingBean;
import com.dotstone.chipism.ui.timing.bean.DeleteTimingBean;
import com.dotstone.chipism.ui.timing.bean.SocketTimingData;
import com.dotstone.chipism.ui.timing.bean.TimingData;
import com.dotstone.chipism.ui.view.DevicePopWindow;
import com.dotstone.chipism.ui.view.SideSlipItem;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.SPUtils;
import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.nostra13.universalimageloader.utils.L;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class RemoteSocketTimingActivity extends BaseActivity {
    private TextView tvTitle;
    private ListView lv_timing;
    private TextView mStatusBar;
    private ImageView btnAdd;
    private View layoutBack;
    private MyTimingAdapter adapter;
    private List<TimingData> datas = new ArrayList<>();
    private SVProgressHUD mSVProgressHUD;
    private RelativeLayout emptyView;
    public static RemoteSocketTimingActivity instance;
    public int addflag;
    private String deviceid;


    @Override
    public void widgetClick(View v) {
        switch (v.getId()){
            case R.id.nextstep:
                Intent intent = new Intent(this , AddSocketTiming1Activity.class);
                intent.putExtra("addflag",1);
                intent.putExtra("deviceid",deviceid);
                startActivityForResult(intent , AddSocketTimingActivity.ADD_SUCCESS_REQUEST_CODE);
                break;
            case R.id.back_layout:
                finish();
                break;
        }
    }

    @Override
    public void initParms(Bundle parms) {
//        device = DeviceManager.getInstance().getDeviceById(id);
    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_remote_socket_timing;
    }

    @Override
    public void initView(View view) {
        instance=this;
        lv_timing = $(R.id.lv_socket_timing);
        mStatusBar = $(R.id.tv_statusBar_mian);
        tvTitle = $(R.id.title_tv);
        btnAdd = $(R.id.nextstep);
        layoutBack = $(R.id.back_layout);
        mSVProgressHUD = new SVProgressHUD(this);
        emptyView = $(R.id.emptyView);
        deviceid = getIntent().getStringExtra("deviceid");
        lv_timing.setEmptyView(emptyView);
        adapter = new MyTimingAdapter();
    }

    @Override
    public void setListener() {
        lv_timing.setAdapter(adapter);

        tvTitle.setText("定时");
       // btnAdd.setText("添加");
        btnAdd.setVisibility(View.VISIBLE);
        mStatusBar.setVisibility(View.VISIBLE);
        btnAdd.setOnClickListener(this);
        layoutBack.setOnClickListener(this);

        lv_timing.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                TimingData timingData = datas.get(position);
                //传递给下一个界面进行修改
                Intent intent = new Intent(RemoteSocketTimingActivity.this , AddSocketTiming1Activity.class);
                intent.putExtra("timingData" , timingData);
                intent.putExtra("addflag",2);
                intent.putExtra("pushweek",""+timingData.getPush_week());
                intent.putExtra("iscycle",timingData.isCycle());
                startActivityForResult(intent ,  AddSocketTimingActivity.ADD_SUCCESS_REQUEST_CODE);
            }
        });
        ItemOnLongClick();
    }

    /**
     * 查询数据
     */
    private void queryData(){
        mSVProgressHUD.showWithStatus("正在获取数据");

        Log.i("我的天" , "haha :" + new Gson().toJson(new AddTimingBean()));
        JSONObject obj = new JSONObject();
        try{
            obj.put("hid",  DeviceManager.getInstance().hid);
            obj.put("key", "10000");

            obj.put("requestTime", "" + System.currentTimeMillis());
            obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
        //获取定时数据
        OkHttpUtils.postString().url(HttpURL.GET_TIMING)
                .mediaType(MediaType.parse("application/json;charset=UTF-8"))
                .content(obj.toString())
                .build().readTimeOut(5000)
                .writeTimeOut(5000).connTimeOut(5000)
                .execute(new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {
                        showToast("获取数据失败");
                        mSVProgressHUD.dismiss();
                    }

                    @Override
                    public void onResponse(String response) {
                        mSVProgressHUD.dismiss();
                        Log.i("我我我", "response");
                        try{
                            SocketTimingData data = new Gson().fromJson(response , SocketTimingData.class);
                            Log.i("我我我", "response:" + new Gson().toJson(data));
                            if (data.getResultCode().equals("1")){
                                datas.clear();
                                //倒叙排列
                                Collections.reverse(data.getData());
                               for (TimingData data1:  data.getData()) {
                                    String did=data1.getDid()+"";
                                    Log.e("",did);
                                   if(did.equals(deviceid)){
                                       datas.add(data1);
                                   }else {

                                   }
                                }
                           //  datas.addAll(data.getData());
                                adapter.notifyDataSetChanged();
                            }
                        }catch (JsonIOException e){
                            e.printStackTrace();
                            showToast("数据异常");
                        }
                    }
                });
    }

    @Override
    public void doBusiness(Context mContext) {
        queryData();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i("onActivityResult" ,"进来了" + requestCode + "---" + resultCode);
        if (requestCode == AddSocketTimingActivity.ADD_SUCCESS_REQUEST_CODE && resultCode == AddSocketTimingActivity.ADD_SUCCESS_RESULT_CODE){
            queryData();
        }
    }




    class MyTimingAdapter extends BaseAdapter{


        @Override
        public int getCount() {
            return datas.size();
        }

        @Override
        public Object getItem(int i) {
            return datas.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            ViewHolder viewHolder = null;
            if (view == null) {
                view = LayoutInflater.from(RemoteSocketTimingActivity.this ).inflate(R.layout.item_socket_timing , null , false);
                viewHolder = new ViewHolder(view);
                viewHolder.item_layout_timing= (LinearLayout) view.findViewById(R.id.item_layout_timing);
                viewHolder.item_tv_timing_content=(TextView)view.findViewById(R.id.item_tv_timing_content);
                viewHolder.ibOffOn=(ImageButton)view.findViewById(R.id.onoff_tgl);
                view.setTag(viewHolder);
            }
            if (viewHolder == null) {
                viewHolder = (ViewHolder) view.getTag();
            }
            //处理业务
            String  days=  parseRepeat(datas.get(i).getPush_week(),0);
            if(datas.get(i).getTaskName().equals("关")){
                if(datas.get(i).isCycle()){
                    viewHolder.item_tv_timing_content.setText("关闭时间 " + datas.get(i).getPushTime()+"\n"+days);
                }else{
                    viewHolder.item_tv_timing_content.setText("关闭时间 " + datas.get(i).getPushTime()+"\n"+"执行一次");
                }

            }else if(datas.get(i).getTaskName().equals("开")){
                if(datas.get(i).isCycle()){
                    viewHolder.item_tv_timing_content.setText("开启时间 " + datas.get(i).getPushTime()+"\n"+days);
                }else{
                    viewHolder.item_tv_timing_content.setText("开启时间 " + datas.get(i).getPushTime()+"\n"+"执行一次");
                }

            }
          //  viewHolder.item_tv_timing_content.setText(datas.get(i).getTaskName() +" " + datas.get(i).getPushTime());
//            viewHolder.tbOffOn.setChecked(datas.get(i).isOpen());
            viewHolder.ibOffOn.setTag(i);
           viewHolder.ibOffOn.setImageResource(datas.get(i).getTaskStatus() == 1 ? R.drawable.butn_open : R.drawable.butn_close);
           viewHolder.ibOffOn.setOnClickListener(myToggleButtonOnClickListener);



        //    viewHolder.item_layout_timing.setTag(i);
         //   viewHolder.item_layout_timing.setOnClickListener(myLayoutOnClickListener);
            return view;
        }


        /**
         * @param repeat 解析二进制闹钟周期
         * @param flag   flag=0返回带有汉字的周一，周二cycle等，flag=1,返回weeks(1,2,3)
         * @return
         */
        public  String parseRepeat(int repeat, int flag) {
            String cycle = "";
            String weeks = "";
            if (repeat == 0) {
                repeat = 127;
            }
            if (repeat % 2 == 1) {
                cycle = "周一";
                weeks = "1";
            }
            if (repeat % 4 >= 2) {
                if ("".equals(cycle)) {
                    cycle = "周二";
                    weeks = "2";
                } else {
                    cycle = cycle + "," + "周二";
                    weeks = weeks + "," + "2";
                }
            }
            if (repeat % 8 >= 4) {
                if ("".equals(cycle)) {
                    cycle = "周三";
                    weeks = "3";
                } else {
                    cycle = cycle + "," + "周三";
                    weeks = weeks + "," + "3";
                }
            }
            if (repeat % 16 >= 8) {
                if ("".equals(cycle)) {
                    cycle = "周四";
                    weeks = "4";
                } else {
                    cycle = cycle + "," + "周四";
                    weeks = weeks + "," + "4";
                }
            }
            if (repeat % 32 >= 16) {
                if ("".equals(cycle)) {
                    cycle = "周五";
                    weeks = "5";
                } else {
                    cycle = cycle + "," + "周五";
                    weeks = weeks + "," + "5";
                }
            }
            if (repeat % 64 >= 32) {
                if ("".equals(cycle)) {
                    cycle = "周六";
                    weeks = "6";
                } else {
                    cycle = cycle + "," + "周六";
                    weeks = weeks + "," + "6";
                }
            }
            if (repeat / 64 == 1) {
                if ("".equals(cycle)) {
                    cycle = "周日";
                    weeks = "7";
                } else {
                    cycle = cycle + "," + "周日";
                    weeks = weeks + "," + "7";
                }
            }

            return flag == 0 ? cycle : weeks;
        }

        class ViewHolder{
            TextView item_tv_timing_content;
            ImageButton ibOffOn;
            LinearLayout item_layout_timing;

            public ViewHolder(View view){

                item_layout_timing= (LinearLayout) view.findViewById(R.id.item_layout_timing);
                item_tv_timing_content = (TextView) view.findViewById(R.id.item_tv_timing_content);
                ibOffOn = (ImageButton) view.findViewById(R.id.onoff_tgl);

            }
        }

        /**
           * ToggleButton点击的监听
           */
         private View.OnClickListener myToggleButtonOnClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final int index = (int) view.getTag();
                final ImageButton imageButton = (ImageButton) view;
//                //在这里做定时开关的操作
//                //这里访问网络
                mSVProgressHUD.showSuccessWithStatus("执行中...");
                JSONObject obj = new JSONObject();
                try{
                    obj.put("hid",  DeviceManager.getInstance().hid);
                    obj.put("id",  datas.get(index).getTaskId());
                    obj.put("key", "10000");

                    int push_week = datas.get(index).getPush_week();
                    String numberStr = getBit((byte) push_week);

                    int number = 0;
                    for (int i = 0 ; i < numberStr.length(); i ++){
                        if (numberStr.charAt(i) == '1'){
                            number ++;
                        }
                    }
                    obj.put("reSendNumber", number);

                    obj.put("requestTime", "" + System.currentTimeMillis());

                    obj.put("taskStatus", datas.get(index).getTaskStatus() == 1 ? 2 : 1);
                    obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
                } catch (JSONException e1) {
                    e1.printStackTrace();
                }

                //获取定时数据
                OkHttpUtils.postString().url(HttpURL.UPDATA_TIMING_STATUS)
                        .mediaType(MediaType.parse("application/json;charset=UTF-8"))
                        .content(obj.toString())
                        .build().readTimeOut(5000)
                        .writeTimeOut(5000).connTimeOut(5000)
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Request request, Exception e) {
                                showToast("执行失败");
                                mSVProgressHUD.dismiss();
                            }

                            @Override
                            public void onResponse(String response) {
                                mSVProgressHUD.dismiss();
                                try{

                                    DeleteTimingBean data = new Gson().fromJson(response , DeleteTimingBean.class);
                                    Log.i("我我我", "response:" + response);
                                    if (data.getResultCode().equals("1")){
                                        datas.get(index).setTaskStatus(datas.get(index).getTaskStatus() == 1 ? 2 :1);
                                        imageButton.setImageResource(datas.get(index).getTaskStatus() == 1 ? R.drawable.butn_open : R.drawable.butn_close);
                                    }
                                }catch (JsonIOException e){
                                    e.printStackTrace();
                                    showToast("数据异常");
                                }
                            }
                        });

//                datas.get(index).setOpen(!datas.get(index).isOpen());
//                ((ToggleButton)view).setChecked(false);
            }
        };




        private View.OnClickListener myBtnDeleteOnClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final int index = (int) view.getTag();
                mSVProgressHUD.showErrorWithStatus("正在删除中...");
                JSONObject obj = new JSONObject();
                try{
                    obj.put("hid",  DeviceManager.getInstance().hid);
                    obj.put("id",  datas.get(index).getTaskId());
                    obj.put("key", "10000");
                    obj.put("requestTime", "" + System.currentTimeMillis());
                    obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
                } catch (JSONException e1) {
                    e1.printStackTrace();
                }

                Log.i("我我我", "response111:" + obj.toString());
                //获取定时数据
                OkHttpUtils.postString().url(HttpURL.DELETE_TIMING)
                        .mediaType(MediaType.parse("application/json;charset=UTF-8"))
                        .content(obj.toString())
                        .build().readTimeOut(5000)
                        .writeTimeOut(5000).connTimeOut(5000)
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Request request, Exception e) {
                                showToast("删除失败");
                                mSVProgressHUD.dismiss();
                            }

                            @Override
                            public void onResponse(String response) {
                                mSVProgressHUD.dismiss();
                                try{

                                    DeleteTimingBean data = new Gson().fromJson(response , DeleteTimingBean.class);
                                    Log.i("我我我", "response:" + response);
                                    if (data.getResultCode().equals("1")){
                                        showToast("删除成功");
                                        datas.remove(index);
                                        adapter.notifyDataSetChanged();
                                    }
                                }catch (JsonIOException e){
                                    e.printStackTrace();
                                    showToast("数据异常");
                                }
                            }
                        });
            }
        };

        /**
         * 点击布局事件，进行修改
         */
        private View.OnClickListener myLayoutOnClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final int index = (int) view.getTag();
                TimingData timingData = datas.get(index);
                //传递给下一个界面进行修改
                Intent intent = new Intent(RemoteSocketTimingActivity.this , AddSocketTiming1Activity.class);
                intent.putExtra("timingData" , timingData);
                startActivityForResult(intent ,  AddSocketTimingActivity.ADD_SUCCESS_REQUEST_CODE);
            }
        };
    }

    public static String getBit(byte by){
        StringBuffer sb = new StringBuffer();
        sb.append((by>>7)&0x1)
                .append((by>>6)&0x1)
                .append((by>>5)&0x1)
                .append((by>>4)&0x1)
                .append((by>>3)&0x1)
                .append((by>>2)&0x1)
                .append((by>>1)&0x1)
                .append((by>>0)&0x1);
        return sb.toString();
    }



    // 注：setOnCreateContextMenuListener是与下面onContextItemSelected配套使用的
    private void ItemOnLongClick() {
        lv_timing
                .setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                    @Override
                    public boolean onItemLongClick(AdapterView<?> parent,
                                                   View view, int position, long id) {
                        new DevicePopWindow(RemoteSocketTimingActivity.this,view,position)
                                .showPopupWindow(tvTitle);
                        return true;
                    }
                });

    }


    /**
     * 删除点击的监听
     */

    public void deleteItem(final int position) {
        mSVProgressHUD.showErrorWithStatus("正在删除中...");
        JSONObject obj = new JSONObject();
        try{
            obj.put("hid",  DeviceManager.getInstance().hid);
            obj.put("id",  datas.get(position).getTaskId());
            obj.put("key", "10000");
            obj.put("requestTime", "" + System.currentTimeMillis());
            obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
        } catch (JSONException e1) {
            e1.printStackTrace();
        }

        Log.i("我我我", "response111:" + obj.toString());
        //获取定时数据
        OkHttpUtils.postString().url(HttpURL.DELETE_TIMING)
                .mediaType(MediaType.parse("application/json;charset=UTF-8"))
                .content(obj.toString())
                .build().readTimeOut(5000)
                .writeTimeOut(5000).connTimeOut(5000)
                .execute(new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {
                        showToast("删除失败");
                        mSVProgressHUD.dismiss();
                    }

                    @Override
                    public void onResponse(String response) {
                        mSVProgressHUD.dismiss();
                        try{

                            DeleteTimingBean data = new Gson().fromJson(response , DeleteTimingBean.class);
                            Log.i("我我我", "response:" + response);
                            if (data.getResultCode().equals("1")){
                                showToast("删除成功");
                                datas.remove(position);
                                adapter.notifyDataSetChanged();
                            }
                        }catch (JsonIOException e){
                            e.printStackTrace();
                            showToast("数据异常");
                        }
                    }
                });
    }


}
